import base64
import binascii

from Crypto.Cipher import AES
from django.utils.safestring import mark_safe
from django.conf import settings
from django import template

register = template.Library()

def pad_string (str, block_size):
	numpad = block_size - (len (str) % block_size)
	return str + numpad * chr (numpad)

def enc_string(str):
	key = binascii.unhexlify(settings.MAILHIDE_PRIV_KEY)
	mode = AES.MODE_CBC
	iv = '\000' * 16
	obj = AES.new(key, mode, iv)
	return obj.encrypt(str)

@register.filter()
def mailhide(value):
	args = {}
	padded_value = pad_string(value, 16)
	encrypted_value = enc_string(padded_value)
	
	args['public_key'] = settings.MAILHIDE_PUB_KEY
	args['encrypted_email'] = base64.urlsafe_b64encode(encrypted_value)
	args['domain'] = value[value.index('@')+1:]
	
	result =  '''<a href="http://mailhide.recaptcha.net/d?k=%(public_key)s&amp;c=%(encrypted_email)s"
				onclick="window.open('http://mailhide.recaptcha.net/d?k=%(public_key)s&amp;c=%(encrypted_email)s', '',
				'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300');
				return false;" title="Reveal this e-mail address">...@%(domain)s</a>''' % args

	return mark_safe(result)
